package com.sb.repositories;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import com.sb.model.Role;
import com.sb.model.User;

public class UserRepositoryImpl implements UserRepository {
	
	private SimpleJdbcTemplate jdbcTemplate;
	
	public UserRepositoryImpl(SimpleJdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}


	public User byUserName(String username) {
		return jdbcTemplate.queryForObject("select id, username, password, is_non_expired, is_non_locked, enabled from Users where username = ?",
				new RowMapper<User>() {
			public User mapRow(ResultSet rs, int rowNum) throws SQLException {
				Set<Role> roles = new HashSet<Role>(userRoles(rs.getInt("id")));
				return new User(rs.getInt("id"),rs.getString("username"), rs.getString("password"),rs.getBoolean("is_non_expired"),rs.getBoolean("is_non_locked"),rs.getBoolean("enabled"),roles);
			}

			
		}, username);
	}
	
	private List<Role> userRoles(Integer userId) {
		return jdbcTemplate.query("select id, authority from authorities where user_id = ?", new RowMapper<Role>(){
			public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
				return new Role(rs.getString("authority"));
			}
		},userId);
	}
}
